package com.tencent.examples.core.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.tencent.examples.blueking.mysql.model.BkMessage;
import com.tencent.examples.blueking.mysql.service.MessageService;
import com.tencent.examples.core.processor.MessageProcessor;
import com.tencent.examples.core.processor.common.BkobjidEnum;
import com.tencent.examples.core.processor.mq.MQConnect;
import com.tencent.examples.core.service.IBkMessageService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @author :  CHENWEN
 * @Description :
 * @Creation Date:  2019/3/28
 */
@Service
public class BkMessageServiceImpl implements IBkMessageService {
    @Autowired
    MessageProcessor messageProcessor;
    @Autowired
    MessageService messageService;

    @Override
    public void syncStore() {
        //获取未同步的信息
        Page<BkMessage> messagePage = messageService.getMessageList(null, BkMessage.builder()
                .sync(0)
                .build());
        List<BkMessage> messageList = messagePage.getContent();
        if (CollectionUtils.isEmpty(messageList)) {
            return;
        }
        messageList.forEach(bkMessage -> {
            try {
                if (StringUtils.isBlank(bkMessage.getTopic()) || MQConnect.CATTRIB_NAME.equals(bkMessage.getTopic())) {
                    JSONObject syncData = JSONObject.parseObject(bkMessage.getMessage());
                    if (bkMessage.getSource().equals(BkobjidEnum.jk.name())) {//mq类型
                        messageProcessor.syncStore(BkobjidEnum.jk, syncData, bkMessage.getId());
                    } else if (bkMessage.getSource().equals(BkobjidEnum.itop.name())) {//itop
                        messageProcessor.syncStore(BkobjidEnum.itop, syncData, bkMessage.getId());
                    }
                } else if (MQConnect.CATTRIB_NAME_HOURS.equals(bkMessage.getTopic())) {
                    JSONObject syncData = JSONObject.parseObject(bkMessage.getMessage());
                    if (bkMessage.getSource().equals(BkobjidEnum.jk.name())) {//mq类型
                        messageProcessor.syncStoreHours(BkobjidEnum.jk, syncData, bkMessage.getId());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}
